package com.sunwayworld.basemodule.coredata.judgmentbasis.service.impl;

import com.sunwayworld.basemodule.coredata.judgmentbasis.bean.LimsJudgmentBasisTmAnalyteHighlowBean;
import com.sunwayworld.basemodule.coredata.judgmentbasis.service.LimsJudgmentBasisTmAnalyteHighlowService;
import com.sunwayworld.framework.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.spring.annotation.GikamBean;

import com.sunwayworld.basemodule.coredata.judgmentbasis.dao.LimsJudgmentBasisTmAnalyteDao;
import com.sunwayworld.basemodule.coredata.judgmentbasis.bean.LimsJudgmentBasisTmAnalyteBean;
import com.sunwayworld.basemodule.coredata.judgmentbasis.service.LimsJudgmentBasisTmAnalyteService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;

import java.util.ArrayList;
import java.util.List;

@Repository
@GikamBean
public class LimsJudgmentBasisTmAnalyteServiceImpl implements LimsJudgmentBasisTmAnalyteService {

    @Autowired
    private LimsJudgmentBasisTmAnalyteDao limsJudgmentBasisTmAnalyteDao;

    @Autowired
    @Lazy
    private LimsJudgmentBasisTmAnalyteHighlowService highlowService;

    @Override
    @SuppressWarnings("unchecked")
    public LimsJudgmentBasisTmAnalyteDao getDao() {
        return limsJudgmentBasisTmAnalyteDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        List<LimsJudgmentBasisTmAnalyteBean> analyteBeans = jsonWrapper.parse(LimsJudgmentBasisTmAnalyteBean.class);
        analyteBeans.forEach(e -> e.setId(ApplicationContextHelper.getNextIdentity()));
        getDao().insert(analyteBeans);
        return analyteBeans.get(0).getId();
    }

    @Override
    @Transactional
    public void delete(RestJsonWrapperBean wrapper) {
        List<LimsJudgmentBasisTmAnalyteBean> parse = wrapper.parse(LimsJudgmentBasisTmAnalyteBean.class);
        if(CollectionUtils.isEmpty(parse)) return;
        // 级联删除
        List<LimsJudgmentBasisTmAnalyteHighlowBean> tmAnalyteHighlowBeans = new ArrayList<>();
        parse.forEach(e -> {
            LimsJudgmentBasisTmAnalyteHighlowBean highlowBean = new LimsJudgmentBasisTmAnalyteHighlowBean();
            highlowBean.setJudgAnalyteId(e.getId());
            tmAnalyteHighlowBeans.add(highlowBean);
        });
        highlowService.getDao().deleteBy(tmAnalyteHighlowBeans, "judgAnalyteId");
        getDao().deleteBy(parse);
    }
}
